<div class="selenium-notes">
<h1>Relative XPath in Selenium</h1>
<p>Relative XPath is an XPath expression used in Selenium WebDriver to locate web elements without specifying the complete path from the root of the HTML document. Instead of following every level of the DOM hierarchy, Relative XPath starts from a particular point and identifies the required element using tag names, attributes, text, indexes, relationships, or other XPath functions.</p>
<p>Relative XPath is commonly used for locating web elements such as input fields, buttons, links, checkboxes, dropdowns, forms, tables, and dynamically generated elements. Selenium training at JustAcademy includes locators such as XPath and CSS selectors as part of Selenium WebDriver and web-element automation. <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">JustAcademy Selenium Training Course</a></p>
<p>You can also visit the <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Selenium Course Demo Registration</a> page for course-demo information.</p>
<hr>
<h2>1. What is Relative XPath?</h2>
<p>Relative XPath is an XPath expression that locates an element from a specific point in the DOM instead of starting from the root of the HTML document.</p>
<p>The most common Relative XPath syntax starts with double forward slashes:</p>
<pre><code>//tagname</code></pre>
<p>For example:</p>
<pre><code>//input</code></pre>
<p>This expression searches for input elements in the document without specifying the complete HTML hierarchy.</p>
<hr>
<h2>2. Basic Syntax of Relative XPath</h2>
<p>The general syntax of Relative XPath is:</p>
<pre><code>//tagname</code></pre>
<p>Relative XPath can also use attributes:</p>
<pre><code>//tagname[@attribute='value']</code></pre>
<p>Example:</p>
<pre><code>//input[@id='username']</code></pre>
<p>This XPath searches for an input element whose ID attribute is username.</p>
<hr>
<h2>3. Why is Relative XPath Used in Selenium?</h2>
<p>Relative XPath provides a flexible way to locate web elements without depending on the complete DOM hierarchy.</p>
<p>It can be used to:</p>
<ul>
<li>Locate elements using attributes.</li>
<li>Locate elements using visible text.</li>
<li>Locate elements using partial attribute values.</li>
<li>Locate elements using indexes.</li>
<li>Navigate between parent and child elements.</li>
<li>Navigate between sibling elements.</li>
<li>Locate dynamically generated elements.</li>
<li>Work with deeply nested elements.</li>
<li>Reduce dependency on the complete HTML structure.</li>
<li>Create reusable Selenium locators.</li>
</ul>
<hr>
<h2>4. Absolute XPath vs Relative XPath</h2>
<p>Absolute XPath follows the complete path from the root of the HTML document.</p>
<pre><code>/html/body/div/form/input</code></pre>
<p>Relative XPath identifies the element without specifying the complete path.</p>
<pre><code>//input</code></pre>
<p>A more specific Relative XPath can be:</p>
<pre><code>//input[@id='username']</code></pre>
<hr>
<h2>5. Relative XPath Starts with Double Slash</h2>
<p>Relative XPath commonly starts with two forward slashes.</p>
<pre><code>//input
//button
//a
//div
//form</code></pre>
<p>The double slash allows XPath to search for matching elements anywhere in the document relative to the current context.</p>
<hr>
<h2>6. Relative XPath Using Tag Name</h2>
<p>The simplest Relative XPath uses only the tag name.</p>
<pre><code>//input</code></pre>
<p>This searches for input elements.</p>
<p>Other examples:</p>
<pre><code>//button
//a
//div
//form
//table
//tr
//td</code></pre>
<p>When many elements have the same tag name, additional conditions should be used to identify the required element.</p>
<hr>
<h2>7. Relative XPath Using ID Attribute</h2>
<p>An ID is one of the most commonly used attributes with Relative XPath.</p>
<p>Consider:</p>
<pre><code><input id="username" type="text"></code></pre>
<p>The Relative XPath is:</p>
<pre><code>//input[@id='username']</code></pre>
<p>Selenium example:</p>
<pre><code>driver.findElement(By.xpath("//input[@id='username']")).sendKeys("admin");</code></pre>
<hr>
<h2>8. Relative XPath Using Name Attribute</h2>
<p>The name attribute can also be used to identify an element.</p>
<pre><code><input type="text" name="username"></code></pre>
<p>XPath:</p>
<pre><code>//input[@name='username']</code></pre>
<p>Selenium:</p>
<pre><code>driver.findElement(By.xpath("//input[@name='username']")).sendKeys("admin");</code></pre>
<hr>
<h2>9. Relative XPath Using Class Attribute</h2>
<p>The class attribute can be used to locate an element.</p>
<pre><code><input class="login-input" type="text"></code></pre>
<p>XPath:</p>
<pre><code>//input[@class='login-input']</code></pre>
<p>Selenium:</p>
<pre><code>driver.findElement(By.xpath("//input[@class='login-input']")).sendKeys("admin");</code></pre>
<p>When an element contains multiple classes, exact class matching may not always be suitable. In such cases, contains() can be useful.</p>
<hr>
<h2>10. Relative XPath Using Multiple Attributes</h2>
<p>Multiple attributes can be combined when one attribute is not sufficient to identify an element uniquely.</p>
<p>HTML:</p>
<pre><code><input id="username" name="user" type="text"></code></pre>
<p>XPath:</p>
<pre><code>//input[@id='username' and @name='user']</code></pre>
<p>Selenium:</p>
<pre><code>driver.findElement(
By.xpath("//input[@id='username' and @name='user']")
);</code></pre>
<hr>
<h2>11. Relative XPath Using the AND Operator</h2>
<p>The <strong>and</strong> operator is used when multiple conditions must be true.</p>
<pre><code>//input[@type='text' and @name='username']</code></pre>
<p>This XPath searches for an input element where both conditions are satisfied.</p>
<hr>
<h2>12. Relative XPath Using the OR Operator</h2>
<p>The <strong>or</strong> operator can be used when either of the conditions can identify the element.</p>
<pre><code>//input[@id='username' or @name='username']</code></pre>
<p>This XPath matches an input where either the ID or name matches username.</p>
<hr>
<h2>13. Relative XPath Using Text</h2>
<p>The <strong>text()</strong> function can locate an element based on its visible text.</p>
<p>HTML:</p>
<pre><code><button>Login</button></code></pre>
<p>XPath:</p>
<pre><code>//button[text()='Login']</code></pre>
<p>Selenium:</p>
<pre><code>driver.findElement(By.xpath("//button[text()='Login']")).click();</code></pre>
<hr>
<h2>14. Relative XPath Using Partial Text</h2>
<p>The <strong>contains()</strong> function can be used when only part of the visible text is known.</p>
<p>HTML:</p>
<pre><code><button>Login to Application</button></code></pre>
<p>XPath:</p>
<pre><code>//button[contains(text(),'Login')]</code></pre>
<p>This can match a button containing the word Login.</p>
<hr>
<h2>15. Relative XPath Using contains()</h2>
<p>The contains() function is useful when an attribute value is dynamic or only part of the value is stable.</p>
<p>HTML:</p>
<pre><code><input id="user_12345" type="text"></code></pre>
<p>XPath:</p>
<pre><code>//input[contains(@id,'user_')]</code></pre>
<p>This XPath searches for an input whose ID contains user_.</p>
<hr>
<h2>16. Relative XPath Using starts-with()</h2>
<p>The starts-with() function can identify elements whose attribute value starts with a specific string.</p>
<p>HTML:</p>
<pre><code><input id="username_12345" type="text"></code></pre>
<p>XPath:</p>
<pre><code>//input[starts-with(@id,'username_')]</code></pre>
<p>This is useful when an application generates dynamic IDs with a stable prefix.</p>
<hr>
<h2>17. Relative XPath Using normalize-space()</h2>
<p>The normalize-space() function removes leading and trailing whitespace and normalizes whitespace in text.</p>
<p>Example:</p>
<pre><code>//button[normalize-space()='Login']</code></pre>
<p>This can be useful when the visible text contains unnecessary spaces or formatting differences.</p>
<hr>
<h2>18. Relative XPath Using Index</h2>
<p>Indexes can be used when multiple elements match the same XPath.</p>
<p>For example:</p>
<pre><code>(//input)[1]</code></pre>
<p>This selects the first input matching the expression.</p>
<pre><code>(//input)[2]</code></pre>
<p>This selects the second input.</p>
<p>Indexes should be used carefully because the position of elements can change when the DOM changes.</p>
<hr>
<h2>19. Relative XPath with Position()</h2>
<p>The position() function can be used to identify an element at a particular position.</p>
<pre><code>//input[position()=1]</code></pre>
<p>Another example:</p>
<pre><code>//input[position()=2]</code></pre>
<p>This can be useful when working with multiple similar elements.</p>
<hr>
<h2>20. Relative XPath for Buttons</h2>
<p>Consider:</p>
<pre><code><button id="loginBtn">Login</button></code></pre>
<p>Possible XPath expressions are:</p>
<pre><code>//button[@id='loginBtn']</code></pre>
<p>Or:</p>
<pre><code>//button[text()='Login']</code></pre>
<p>Or:</p>
<pre><code>//button[contains(text(),'Login')]</code></pre>
<p>Selenium example:</p>
<pre><code>driver.findElement(By.xpath("//button[@id='loginBtn']")).click();</code></pre>
<hr>
<h2>21. Relative XPath for Links</h2>
<p>HTML:</p>
<pre><code><a href="/home">Home</a></code></pre>
<p>XPath using text:</p>
<pre><code>//a[text()='Home']</code></pre>
<p>XPath using href:</p>
<pre><code>//a[@href='/home']</code></pre>
<p>XPath using contains:</p>
<pre><code>//a[contains(@href,'home')]</code></pre>
<hr>
<h2>22. Relative XPath for Checkboxes</h2>
<p>HTML:</p>
<pre><code><input type="checkbox" id="terms"></code></pre>
<p>XPath:</p>
<pre><code>//input[@id='terms']</code></pre>
<p>Selenium:</p>
<pre><code>driver.findElement(By.xpath("//input[@id='terms']")).click();</code></pre>
<hr>
<h2>23. Relative XPath for Radio Buttons</h2>
<p>HTML:</p>
<pre><code><input type="radio" name="gender" value="male"></code></pre>
<p>XPath:</p>
<pre><code>//input[@type='radio' and @value='male']</code></pre>
<p>Selenium:</p>
<pre><code>driver.findElement(
By.xpath("//input[@type='radio' and @value='male']")
).click();</code></pre>
<hr>
<h2>24. Relative XPath for Dropdown Elements</h2>
<p>HTML:</p>
<pre><code><select id="country">
<option>India</option>
<option>USA</option>
</select></code></pre>
<p>Select element:</p>
<pre><code>//select[@id='country']</code></pre>
<p>Option:</p>
<pre><code>//select[@id='country']/option[text()='India']</code></pre>
<hr>
<h2>25. Relative XPath for Form Elements</h2>
<p>Consider:</p>
<pre><code><form id="loginForm">
<input name="username">
<input name="password">
<button>Login</button>
</form></code></pre>
<p>Username:</p>
<pre><code>//form[@id='loginForm']//input[@name='username']</code></pre>
<p>Password:</p>
<pre><code>//form[@id='loginForm']//input[@name='password']</code></pre>
<p>Login button:</p>
<pre><code>//form[@id='loginForm']//button[text()='Login']</code></pre>
<hr>
<h2>26. Relative XPath Using Parent</h2>
<p>The parent axis can be used to move from an element to its parent.</p>
<p>HTML:</p>
<pre><code><div class="login">
<input id="username">
</div></code></pre>
<p>XPath:</p>
<pre><code>//input[@id='username']/parent::div</code></pre>
<p>This XPath locates the div parent of the username input.</p>
<hr>
<h2>27. Relative XPath Using Child</h2>
<p>The child relationship can be used to navigate from a parent element to a child element.</p>
<pre><code>//div[@class='login']/child::input</code></pre>
<p>A shorter equivalent form can be:</p>
<pre><code>//div[@class='login']/input</code></pre>
<hr>
<h2>28. Relative XPath Using Ancestor</h2>
<p>The ancestor axis finds an element above the current element in the DOM hierarchy.</p>
<pre><code>//input[@id='username']/ancestor::form</code></pre>
<p>This locates the form ancestor of the username input.</p>
<hr>
<h2>29. Relative XPath Using Descendant</h2>
<p>The descendant axis locates elements anywhere below the current element.</p>
<pre><code>//form[@id='loginForm']/descendant::input</code></pre>
<p>This finds input elements that are descendants of the login form.</p>
<hr>
<h2>30. Relative XPath Using Following-Sibling</h2>
<p>The following-sibling axis locates sibling elements that appear after the current element.</p>
<p>HTML:</p>
<pre><code><div>
<label>Username</label>
<input type="text">
</div></code></pre>
<p>XPath:</p>
<pre><code>//label[text()='Username']/following-sibling::input</code></pre>
<hr>
<h2>31. Relative XPath Using Preceding-Sibling</h2>
<p>The preceding-sibling axis locates sibling elements that appear before the current element.</p>
<pre><code>//input[@id='username']/preceding-sibling::label</code></pre>
<p>This can locate the label that appears before the username input.</p>
<hr>
<h2>32. Relative XPath Using Following</h2>
<p>The following axis selects nodes that appear after the current node in the document.</p>
<pre><code>//label[text()='Username']/following::input</code></pre>
<p>This can locate input elements appearing after the username label.</p>
<hr>
<h2>33. Relative XPath Using Preceding</h2>
<p>The preceding axis selects nodes that occur before the current node in the document.</p>
<pre><code>//input[@id='password']/preceding::input</code></pre>
<p>This can locate input elements appearing before the password input.</p>
<hr>
<h2>34. Relative XPath Using Descendant Relationship</h2>
<p>The double slash can also be used to locate descendants without specifying every intermediate element.</p>
<pre><code>//div[@id='login']//input</code></pre>
<p>This searches for input elements anywhere inside the div with ID login.</p>
<hr>
<h2>35. Relative XPath with Multiple Conditions</h2>
<p>Multiple conditions can be combined to create a more specific locator.</p>
<pre><code>//input[@type='text' and @name='username' and @placeholder='Enter Username']</code></pre>
<p>This XPath matches an input where all three conditions are satisfied.</p>
<hr>
<h2>36. Relative XPath with not()</h2>
<p>The not() function can be used when a specific attribute value should be excluded.</p>
<pre><code>//input[not(@disabled)]</code></pre>
<p>This expression identifies input elements that do not have the disabled attribute.</p>
<hr>
<h2>37. Relative XPath Using Multiple Text Conditions</h2>
<p>Multiple conditions can also be applied to visible text.</p>
<pre><code>//button[contains(text(),'Login') and not(@disabled)]</code></pre>
<p>This can identify a button containing Login that is not disabled.</p>
<hr>
<h2>38. Relative XPath for Dynamic IDs</h2>
<p>Dynamic web applications sometimes generate changing ID values.</p>
<p>For example:</p>
<pre><code><input id="user_12345" type="text"></code></pre>
<p>On another page load, it may become:</p>
<pre><code><input id="user_67890" type="text"></code></pre>
<p>An XPath using contains() can focus on the stable part:</p>
<pre><code>//input[contains(@id,'user_')]</code></pre>
<hr>
<h2>39. Relative XPath for Dynamic Class Values</h2>
<p>Dynamic applications may also generate changing class names.</p>
<pre><code><button class="btn-login-123">Login</button></code></pre>
<p>XPath:</p>
<pre><code>//button[contains(@class,'btn-login')]</code></pre>
<p>This focuses on the stable portion of the class value.</p>
<hr>
<h2>40. Relative XPath with normalize-space()</h2>
<p>When text contains additional spaces, normalize-space() can make the XPath more reliable.</p>
<p>HTML:</p>
<pre><code><button> Login </button></code></pre>
<p>XPath:</p>
<pre><code>//button[normalize-space()='Login']</code></pre>
<hr>
<h2>41. Relative XPath for Tables</h2>
<p>Relative XPath is useful for navigating tables.</p>
<p>HTML:</p>
<pre><code><table id="employees">
<tbody>
<tr>
<td>John</td>
<td>QA Tester</td>
</tr>
</tbody>
</table></code></pre>
<p>First cell:</p>
<pre><code>//table[@id='employees']//tr[1]/td[1]</code></pre>
<p>Second cell:</p>
<pre><code>//table[@id='employees']//tr[1]/td[2]</code></pre>
<hr>
<h2>42. Relative XPath for Specific Table Data</h2>
<p>Suppose a table contains employee information:</p>
<pre><code><tr>
<td>John</td>
<td>QA Tester</td>
<td>Mumbai</td>
</tr></code></pre>
<p>The XPath for the row containing John can be:</p>
<pre><code>//tr[td[text()='John']]</code></pre>
<p>The city cell in the same row can be located using:</p>
<pre><code>//tr[td[text()='John']]/td[3]</code></pre>
<hr>
<h2>43. Relative XPath Using Text and Parent Relationship</h2>
<p>Suppose:</p>
<pre><code><div>
<span>Username</span>
<input type="text">
</div></code></pre>
<p>The input can be located relative to the Username text:</p>
<pre><code>//span[text()='Username']/following-sibling::input</code></pre>
<p>This approach is useful when the input itself does not have a unique attribute.</p>
<hr>
<h2>44. Relative XPath in Selenium WebDriver</h2>
<p>Selenium uses the By.xpath() locator to work with Relative XPath.</p>
<pre><code>WebElement username = driver.findElement(
By.xpath("//input[@id='username']")
);</code></pre>
<p>The element can then be used for further automation actions.</p>
<hr>
<h2>45. Relative XPath with sendKeys()</h2>
<p>The sendKeys() method can enter text into an element located using Relative XPath.</p>
<pre><code>driver.findElement(
By.xpath("//input[@id='username']")
).sendKeys("admin");</code></pre>
<hr>
<h2>46. Relative XPath with click()</h2>
<p>The click() method can be used after locating a button or link.</p>
<pre><code>driver.findElement(
By.xpath("//button[@id='loginBtn']")
).click();</code></pre>
<hr>
<h2>47. Relative XPath with getText()</h2>
<p>The getText() method retrieves visible text from an element.</p>
<pre><code>String message = driver.findElement(
By.xpath("//div[@class='success-message']")
).getText();
System.out.println(message);</code></pre>
<hr>
<h2>48. Relative XPath with getAttribute()</h2>
<p>The getAttribute() method can retrieve attribute values.</p>
<pre><code>String value = driver.findElement(
By.xpath("//input[@id='username']")
).getAttribute("value");
System.out.println(value);</code></pre>
<hr>
<h2>49. Relative XPath with findElements()</h2>
<p>findElements() can locate multiple elements matching a Relative XPath.</p>
<pre><code>List<WebElement> inputs = driver.findElements(
By.xpath("//input")
);
System.out.println(inputs.size());</code></pre>
<hr>
<h2>50. Relative XPath with Explicit Wait</h2>
<p>Relative XPath can be used with explicit waits when an element needs to become available before interaction.</p>
<pre><code>WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement loginButton = wait.until(
ExpectedConditions.elementToBeClickable(
By.xpath("//button[@id='loginBtn']")
)
);
loginButton.click();</code></pre>
<p>JustAcademy's Selenium curriculum includes waits, synchronization, dynamic elements, and stable test execution strategies as part of Selenium automation training. <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Explore Selenium Training</a></p>
<hr>
<h2>51. Relative XPath in Page Object Model</h2>
<p>Relative XPath locators can be stored in Page Object Model classes.</p>
<pre><code>public class LoginPage {
private WebDriver driver;
private By username =
By.xpath("//input[@id='username']");
private By password =
By.xpath("//input[@id='password']");
private By loginButton =
By.xpath("//button[@id='loginBtn']");
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public void login(String user, String pass) {
driver.findElement(username).sendKeys(user);
driver.findElement(password).sendKeys(pass);
driver.findElement(loginButton).click();
}
}</code></pre>
<hr>
<h2>52. Complete Relative XPath Login Example</h2>
<pre><code>import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class RelativeXPathExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com/login");
driver.findElement(
By.xpath("//input[@id='username']")
).sendKeys("admin");
driver.findElement(
By.xpath("//input[@id='password']")
).sendKeys("admin123");
driver.findElement(
By.xpath("//button[@id='loginBtn']")
).click();
driver.quit();
}
}</code></pre>
<hr>
<h2>53. Relative XPath vs Absolute XPath</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Feature</th><th>Absolute XPath</th><th>Relative XPath</th></tr>
<tr><td>Starting Point</td><td>Starts from the root</td><td>Can locate from a selected context</td></tr>
<tr><td>Common Syntax</td><td>/html/body/div</td><td>//div</td></tr>
<tr><td>Path</td><td>Complete DOM path</td><td>Targeted path</td></tr>
<tr><td>Length</td><td>Usually longer</td><td>Usually shorter</td></tr>
<tr><td>DOM Dependency</td><td>Highly dependent on hierarchy</td><td>Can use attributes and relationships</td></tr>
<tr><td>Dynamic Pages</td><td>Can be sensitive to structural changes</td><td>Can be constructed around stable attributes</td></tr>
<tr><td>Example</td><td>/html/body/div/form/input</td><td>//input[@id='username']</td></tr>
</table>
<hr>
<h2>54. Relative XPath vs ID Locator</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Feature</th><th>Relative XPath</th><th>ID Locator</th></tr>
<tr><td>Selenium Method</td><td>By.xpath()</td><td>By.id()</td></tr>
<tr><td>Identification</td><td>Can use attributes, text, relationships, and functions</td><td>Uses ID attribute</td></tr>
<tr><td>Flexibility</td><td>High</td><td>Depends on ID availability</td></tr>
<tr><td>Example</td><td>//input[@id='username']</td><td>username</td></tr>
</table>
<hr>
<h2>55. Advantages of Relative XPath</h2>
<ul>
<li>It does not require the complete DOM hierarchy.</li>
<li>It can create shorter XPath expressions.</li>
<li>It can use element attributes.</li>
<li>It can use visible text.</li>
<li>It supports XPath functions such as contains() and starts-with().</li>
<li>It supports parent-child relationships.</li>
<li>It supports sibling relationships.</li>
<li>It can be used for dynamic elements when stable parts of attributes are available.</li>
<li>It can be used with Page Object Model.</li>
<li>It can be used with explicit waits.</li>
</ul>
<hr>
<h2>56. Disadvantages of Relative XPath</h2>
<ul>
<li>A poorly designed Relative XPath can match multiple elements.</li>
<li>Changing attributes can make attribute-based XPath invalid.</li>
<li>Incorrect indexes can identify the wrong element.</li>
<li>Complex XPath expressions can become difficult to understand.</li>
<li>Dynamic text can affect text-based XPath.</li>
<li>Using too many conditions can make the XPath unnecessarily complicated.</li>
</ul>
<hr>
<h2>57. Common Mistakes in Relative XPath</h2>
<ul>
<li>Using the wrong attribute name.</li>
<li>Using incorrect attribute values.</li>
<li>Forgetting quotation marks around attribute values.</li>
<li>Using text() when the actual text is nested inside another element.</li>
<li>Using an incorrect index.</li>
<li>Creating an XPath that matches multiple elements.</li>
<li>Not validating the XPath in browser Developer Tools.</li>
<li>Using unstable dynamic attributes without a stable pattern.</li>
<li>Writing unnecessarily complicated XPath expressions.</li>
</ul>
<hr>
<h2>58. How to Validate Relative XPath in Chrome</h2>
<ol>
<li>Open the webpage in Chrome.</li>
<li>Right-click the required element.</li>
<li>Select Inspect.</li>
<li>Open the Console tab.</li>
<li>Use the $x() function.</li>
<li>Enter the Relative XPath.</li>
<li>Check the matching element.</li>
<li>Use the validated XPath in Selenium.</li>
</ol>
<p>Example:</p>
<pre><code>$x("//input[@id='username']")</code></pre>
<p>Another example:</p>
<pre><code>$x("//button[text()='Login']")</code></pre>
<hr>
<h2>59. How to Check Whether XPath is Unique</h2>
<p>A good XPath should identify the intended element without unexpectedly matching unrelated elements.</p>
<p>In Chrome Console:</p>
<pre><code>$x("//input[@id='username']")</code></pre>
<p>If one intended element is returned, the expression can be investigated as a unique locator.</p>
<p>If multiple elements are returned, make the XPath more specific.</p>
<pre><code>//form[@id='loginForm']//input[@id='username']</code></pre>
<hr>
<h2>60. Best Practices for Relative XPath</h2>
<ul>
<li>Use stable attributes whenever possible.</li>
<li>Prefer unique attributes for element identification.</li>
<li>Use text-based XPath when visible text is stable.</li>
<li>Use contains() for stable portions of dynamic attributes.</li>
<li>Use starts-with() for predictable dynamic prefixes.</li>
<li>Avoid unnecessary XPath levels.</li>
<li>Use indexes only when necessary.</li>
<li>Validate XPath expressions in Developer Tools.</li>
<li>Keep XPath expressions readable.</li>
<li>Use Page Object Model to organize locators.</li>
<li>Review locators when the UI changes.</li>
<li>Use explicit waits when elements are dynamically loaded.</li>
</ul>
<hr>
<h2>61. When Should You Use Relative XPath?</h2>
<p>Relative XPath can be useful when:</p>
<ul>
<li>An element has a stable ID, name, class, or other attribute that can be used in an XPath expression.</li>
<li>You need to locate an element using visible text.</li>
<li>You need to locate an element using a partial attribute value.</li>
<li>You need to navigate through parent-child relationships.</li>
<li>You need to locate sibling elements.</li>
<li>You are working with nested web elements.</li>
<li>You need to locate elements in dynamic web applications.</li>
<li>You need a targeted XPath instead of a complete DOM path.</li>
</ul>
<hr>
<h2>62. Relative XPath for Dynamic Web Elements</h2>
<p>Dynamic web elements can have changing IDs, classes, or other attributes. Relative XPath can be constructed using stable portions of those values.</p>
<p>Example:</p>
<pre><code><button id="submit_12345">Submit</button></code></pre>
<p>Instead of depending on the complete dynamic value, use:</p>
<pre><code>//button[contains(@id,'submit_')]</code></pre>
<p>This expression focuses on the stable part of the attribute.</p>
<hr>
<h2>63. Relative XPath Using Label Relationships</h2>
<p>Labels can be useful reference points when input fields do not have unique attributes.</p>
<p>HTML:</p>
<pre><code><div>
<label>Email</label>
<input type="email">
</div></code></pre>
<p>XPath:</p>
<pre><code>//label[text()='Email']/following-sibling::input</code></pre>
<p>This finds the input associated with the Email label based on the sibling relationship.</p>
<hr>
<h2>64. Relative XPath for Login Form</h2>
<pre><code><form id="loginForm">
<label>Username</label>
<input id="username" type="text">
<label>Password</label>
<input id="password" type="password">
<button id="loginBtn">Login</button>
</form></code></pre>
<p>Relative XPath expressions:</p>
<pre><code>//form[@id='loginForm']//input[@id='username']
//form[@id='loginForm']//input[@id='password']
//form[@id='loginForm']//button[@id='loginBtn']</code></pre>
<hr>
<h2>65. Real-World Automation Flow</h2>
<pre><code>Open Browser
↓
Open Web Application
↓
Inspect Required Element
↓
Identify Stable Attribute or Relationship
↓
Create Relative XPath
↓
Validate XPath in Browser
↓
Use By.xpath()
↓
Locate WebElement
↓
Perform Action
↓
Validate Result
↓
Continue Test Execution</code></pre>
<hr>
<h2>66. Relative XPath Quick Reference</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Purpose</th><th>Example</th></tr>
<tr><td>Tag Name</td><td>//input</td></tr>
<tr><td>ID</td><td>//input[@id='username']</td></tr>
<tr><td>Name</td><td>//input[@name='username']</td></tr>
<tr><td>Class</td><td>//input[@class='login-input']</td></tr>
<tr><td>Text</td><td>//button[text()='Login']</td></tr>
<tr><td>Contains Text</td><td>//button[contains(text(),'Login')]</td></tr>
<tr><td>Contains Attribute</td><td>//input[contains(@id,'user')]</td></tr>
<tr><td>Starts With</td><td>//input[starts-with(@id,'user_')]</td></tr>
<tr><td>Multiple Conditions</td><td>//input[@type='text' and @name='username']</td></tr>
<tr><td>First Element</td><td>(//input)[1]</td></tr>
<tr><td>Parent</td><td>//input[@id='username']/parent::div</td></tr>
<tr><td>Ancestor</td><td>//input[@id='username']/ancestor::form</td></tr>
<tr><td>Following Sibling</td><td>//label[text()='Username']/following-sibling::input</td></tr>
<tr><td>Descendant</td><td>//form[@id='loginForm']/descendant::input</td></tr>
</table>
<hr>
<h2>67. Practical Exercise</h2>
<p>Create a login page containing:</p>
<ul>
<li>Username field.</li>
<li>Password field.</li>
<li>Remember Me checkbox.</li>
<li>Login button.</li>
<li>Forgot Password link.</li>
</ul>
<p>Create Relative XPath expressions for each element.</p>
<pre><code>//input[@id='username']
//input[@id='password']
//input[@type='checkbox']
//button[text()='Login']
//a[contains(text(),'Forgot Password')]</code></pre>
<p>Validate every XPath using:</p>
<pre><code>$x("YOUR_XPATH")</code></pre>
<hr>
<h2>68. Complete Relative XPath Automation Example</h2>
<pre><code>import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class RelativeXPathAutomation {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com/login");
WebElement username = driver.findElement(
By.xpath("//input[@id='username']")
);
WebElement password = driver.findElement(
By.xpath("//input[@id='password']")
);
WebElement loginButton = driver.findElement(
By.xpath("//button[@id='loginBtn']")
);
username.sendKeys("admin");
password.sendKeys("admin123");
loginButton.click();
driver.quit();
}
}</code></pre>
<hr>
<h2>69. Relative XPath Interview Questions</h2>
<h3>Q1. What is Relative XPath?</h3>
<p>Relative XPath is an XPath expression used to locate an element without specifying its complete path from the root of the HTML document.</p>
<h3>Q2. How does Relative XPath commonly start?</h3>
<p>Relative XPath commonly starts with double forward slashes.</p>
<pre><code>//</code></pre>
<h3>Q3. Give an example of Relative XPath.</h3>
<pre><code>//input[@id='username']</code></pre>
<h3>Q4. What is the difference between Absolute and Relative XPath?</h3>
<p>Absolute XPath follows the complete hierarchy from the root, while Relative XPath can locate an element using attributes, text, relationships, functions, and other targeted conditions.</p>
<h3>Q5. Can Relative XPath use attributes?</h3>
<p>Yes. Attributes such as ID, name, class, type, href, and other HTML attributes can be used.</p>
<h3>Q6. Can Relative XPath use text?</h3>
<p>Yes. The text() function can be used to locate elements based on their visible text.</p>
<h3>Q7. What is contains() in XPath?</h3>
<p>contains() is an XPath function used to match a partial value of an attribute or text.</p>
<h3>Q8. What is starts-with()?</h3>
<p>starts-with() matches an attribute value that begins with a specified string.</p>
<h3>Q9. Can Relative XPath use indexes?</h3>
<p>Yes. Indexes can be used to identify a specific element among multiple matching elements.</p>
<h3>Q10. How can Relative XPath be tested?</h3>
<p>Relative XPath can be tested in the browser Console using the $x() function.</p>
<h3>Q11. Can Relative XPath work with dynamic elements?</h3>
<p>Yes. It can be constructed using stable portions of dynamic attributes, text, and element relationships.</p>
<h3>Q12. Can Relative XPath be used with Selenium?</h3>
<p>Yes. Selenium WebDriver supports Relative XPath through By.xpath().</p>
<hr>
<h2>70. Relative XPath Learning Checklist</h2>
<ul>
<li>Understand XPath basics.</li>
<li>Understand Relative XPath syntax.</li>
<li>Understand the double slash.</li>
<li>Locate elements using tag names.</li>
<li>Locate elements using ID.</li>
<li>Locate elements using name.</li>
<li>Locate elements using class.</li>
<li>Use multiple attributes.</li>
<li>Use and and or operators.</li>
<li>Use text().</li>
<li>Use contains().</li>
<li>Use starts-with().</li>
<li>Use normalize-space().</li>
<li>Use indexes.</li>
<li>Use parent and child relationships.</li>
<li>Use ancestor and descendant axes.</li>
<li>Use following-sibling and preceding-sibling.</li>
<li>Handle dynamic attributes.</li>
<li>Validate XPath in Chrome.</li>
<li>Use Relative XPath with Selenium WebDriver.</li>
<li>Use Relative XPath with Page Object Model.</li>
<li>Practice creating stable XPath expressions.</li>
</ul>
<hr>
<h2>71. Key Points to Remember</h2>
<ul>
<li>Relative XPath commonly starts with //.</li>
<li>It does not require the complete DOM hierarchy.</li>
<li>It can use attributes to locate elements.</li>
<li>It can use visible text.</li>
<li>It supports XPath functions such as contains() and starts-with().</li>
<li>It supports parent, child, ancestor, descendant, and sibling relationships.</li>
<li>It can be used with dynamic elements when stable patterns are available.</li>
<li>Indexes can be used when multiple elements match.</li>
<li>XPath expressions should be validated before automation execution.</li>
<li>Stable and readable XPath expressions are easier to maintain.</li>
<li>Relative XPath is commonly used with Selenium WebDriver through By.xpath().</li>
</ul>
<hr>
<h2>72. Conclusion</h2>
<p>Relative XPath is an important Selenium locator technique that allows testers to locate web elements without depending on the complete path from the HTML root. It can identify elements using attributes, visible text, partial values, indexes, parent-child relationships, sibling relationships, and XPath functions.</p>
<p>Relative XPath is especially useful when creating Selenium automation scripts because it allows testers to build targeted locators around meaningful and stable characteristics of web elements. It can also be used with dynamic web elements when the XPath is designed around stable portions of their attributes or relationships.</p>
<p>JustAcademy's Selenium Automation Testing course covers Selenium WebDriver, locators including XPath and CSS selectors, WebElements, browser automation, waits, dynamic elements, TestNG, Page Object Model, framework development, and practical automation projects. <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Explore JustAcademy Selenium Training</a>.</p>
<p>For additional course information, visit the <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">JustAcademy Selenium Course Demo Registration</a> page.</p>
</div>